package com.tju.resource.server.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tju.resource.common.ServiceException;
import com.tju.resource.mapper.TbCommandMapper;
import com.tju.resource.mapper.TbOrderMapper;
import com.tju.resource.mapper.TbProdPlanMapper;
import com.tju.resource.model.TbCommand;
import com.tju.resource.model.TbOrder;
import com.tju.resource.model.TbProdPlan;
import com.tju.resource.server.TbOrderService;
import com.tju.resource.server.TbProcessGroupService;
import com.tju.resource.server.TbProdPlanService;
import com.tju.resource.tool.result.Result;
import com.tju.resource.tool.result.ResultEnum;
import com.tju.resource.tool.result.ResultUtil;
import com.tju.resource.tool.tool.ClientParameters;
import com.tju.resource.tool.tool.EmptyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@Slf4j
@Service
public class TbProdPlanServiceImpl implements TbProdPlanService {

    @Autowired
    TbProdPlanMapper mapper;
    @Autowired
    TbProcessGroupService pgService;
    @Autowired
    private TbOrderService tbOrderService;
    @Autowired
    private TbCommandMapper tbCommandMapper;

    @Override
    public TbProdPlan get(Long id) {
        return mapper.selectById(id);
    }

    @Override
    public List<TbProdPlan> getByOR(Long orderId) {
        QueryWrapper<TbProdPlan> query = new QueryWrapper<>();

        query.eq("order_id", orderId);
        query.orderByDesc("id");
        return mapper.selectList(query);
    }

    @Override
    public Long getProds(Long orderId) {
        List<TbProdPlan> reList;
        AtomicReference<Long> result = new AtomicReference<>(0L);
        reList = getByOR(orderId);

        if (reList.size() != 0) {
            reList.forEach(plan -> result.updateAndGet(v -> v + (null == plan.getPlanNumber() ? 0L : plan.getPlanNumber())));
        } else {
            return 0L;
        }
        return result.get();
    }

    @Override
    public Result<Object> getAll(ClientParameters params) {
        try {
            Page<TbProdPlan> page = new Page<>(params.getPage(), params.getLimit());
            IPage<TbProdPlan> iPage = mapper.getAll(page, params);
            List<TbProdPlan> records = iPage.getRecords();

            return ResultUtil.success(ResultEnum.SUCCESS, records, iPage.getTotal());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Object> add(TbProdPlan plan) {
        TbOrder tbOrder = tbOrderService.checkOrderNumberUnique(plan.getOrderNumber());

        if (null == tbOrder) {
            throw new ServiceException("该订单号不存在!");
        }

        if (null != plan.getGroupNumber()) {
            if (null == pgService.getProcessGroupById(plan.getGroupNumber())) {
                throw new ServiceException("该工艺流程不存在!");
            }
        }
        if (getProds(tbOrder.getId()) + plan.getPlanNumber() <= tbOrder.getOrderPcs()) {
            plan.setOrderId(tbOrder.getId());
            plan.setCreateTime(new Date());
            mapper.insert(plan);

            return ResultUtil.success(ResultEnum.SUCCESS, "新增生产计划成功!");
        } else {
            return ResultUtil.success(ResultEnum.UNKONW_ERROR, "计划数不能大于订单数!");
        }


    }

    @Override
    @Transactional
    public int addEpt(TbOrder order) {
        TbProdPlan plan = new TbProdPlan();
        plan.setOrderId(order.getId());
        plan.setCreateBy(order.getCreateBy());
        plan.setCreateTime(order.getCreateTime());
        plan.setPlanNumber(1L);
        return mapper.insert(plan);
    }

    @Override
    public Result<Object> upd(TbProdPlan plan) {
        TbOrder tbOrder = tbOrderService.checkOrderNumberUnique(plan.getOrderNumber());
        TbProdPlan tbProdPlan = get(plan.getId());
        Long planNumber = tbProdPlan.getPlanNumber();
        planNumber = planNumber == null ? 0L : planNumber;
        if (null != plan.getGroupNumber()) {
            if (null == pgService.getProcessGroupById(plan.getGroupNumber())) {
                throw new ServiceException("该工艺流程不存在!");
            }
        }
        if (((getProds(tbOrder.getId()) - planNumber) + plan.getPlanNumber()) <= tbOrder.getOrderPcs()) {
            plan.setUpdateTime(new Date());
            mapper.updateById(plan);
            return ResultUtil.success(ResultEnum.SUCCESS, "更新生产计划成功!");
        } else {
            return ResultUtil.success(ResultEnum.UNKONW_ERROR, "计划数不能大于订单数!");
        }


    }

    @Override
    public Result<Object> del(TbProdPlan plan) {
        Long id = plan.getId();
        if (EmptyUtils.isNotEmpty(id)) {
            List<TbCommand> tbCommandList = tbCommandMapper.getTbCommandList(null, id);
            if (tbCommandList.size() != 0) {
                return ResultUtil.error(ResultEnum.UNKONW_ERROR, "该生产计划指令单在用");
            }
            mapper.deleteById(id);
            return ResultUtil.success(ResultEnum.SUCCESS, "删除生产计划成功!");
        } else {
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, "缺少参数");
        }

    }
}
